package com.jnu.myllm.ui;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.models.QwenParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.jnu.myllm.entity.User;
import com.jnu.myllm.server.RecordService;
import com.jnu.myllm.ui.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

@Controller
@CrossOrigin(origins = "*")
public class LlmConrtroller {
    private static final Logger log = LoggerFactory.getLogger(LlmConrtroller.class);
    @Autowired
    private RecordService recordService;
    // 测试
    @RequestMapping("/hello")
    @ResponseBody
    public String test() {
        return "hello,world";
    }

    // 通义千问
    @RequestMapping("/llm/qianwen")
    @ResponseBody
    public Result qianwen(String say, HttpServletRequest request) throws NoApiKeyException, ApiException, InputRequiredException {
        User user = (User) request.getAttribute("user");
        Generation gen = new Generation();
        // 需要修改apikey为自己账号的key
        QwenParam params = QwenParam.builder().model("qwen-turbo")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                //.prompt("角色:你是我的男朋友。功能:当我不开心的时候，你要安慰我，让我开心。例如：我说:真倒霉，下雨天让我的鞋子湿透了，好难受。你就安慰我说：“我今天下雨摔倒了，全身都湿透了，亲爱的，你已经算幸运了。”举例完毕。 用户说:" + say)
                .prompt(say)
                .seed(1234)
                .topP(0.8)
                .resultFormat("message")
                .enableSearch(false)
                .maxTokens(100)
                .temperature((float) 0.85)
                .repetitionPenalty((float) 1.0)
                .build();
        try {
            GenerationResult result = gen.call(params);
            System.out.println(result);
            String msg = result.getOutput().getChoices().get(0).getMessage().getContent();
//            String word = say+"类人";
//            recordService.addRecord(say, word,200, user.getId());
            recordService.addRecord(say, msg, result.getUsage().getTotalTokens(), user.getId());
            return new Result(2000,"请求成功", msg);
        }catch(Exception e){
            return new Result(5000,"模型调用错误："+e.getMessage(),null);
        }
    }
    //private static final String IMAGE_URL = "https://img1.baidu.com/it/u=465289696,3068910287&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1067";
    // 通义万象
    @RequestMapping("/llm/wanxiang")
    @ResponseBody
    public Result wanxiang(String say, int qty, HttpServletRequest request) throws ApiException, NoApiKeyException {
        log.debug("say:{}",say);
        User user = (User) request.getAttribute("user");
        ImageSynthesis is = new ImageSynthesis();
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model("wanx-v1")
                        .prompt(say)
                        .n(qty)
                        .seed(1)
                        .size("1024*1024")
                        .style("<auto>")
                        .build();
//        ImageSynthesisResult result = is.call(param);
//        System.out.println(result);
//        //return result.getOutput().getResults().get(0).get("url");
//        List<String> list = new ArrayList<>();
//        for (int i = 0; i < result.getOutput().getResults().size(); i++) {
//            list.add(result.getOutput().getResults().get(i).get("url"));
//        }
//        return new Result(2000,"请求成功",list);
        try{
            List<String> list = new ArrayList<>();
            StringBuilder wordBuilder = new StringBuilder();
//            for (int i = 0; i < qty; i++) {
//                list.add(IMAGE_URL);
//                wordBuilder.append("图片").append(i + 1).append(": ").append(IMAGE_URL).append("\n");
//            }
//            String word = wordBuilder.toString();
//            recordService.addRecord(say, word,qty*50, user.getId());
            ImageSynthesisResult result = is.call(param);
            System.out.println(result);
            String IMAGE_URL = "";
            for (int i = 0; i < qty; i++) {
                IMAGE_URL = result.getOutput().getResults().get(i).get("url");
                list.add(IMAGE_URL);
                wordBuilder.append("图片").append(i + 1).append(": ").append(IMAGE_URL).append("\n");
            }
            return new Result(2000,"请求成功", list);
        }catch (Exception e){
            return new Result(5000,"调用错误："+e.getMessage(),null);
        }
    }

    // 文心一言
    @RequestMapping("/llm/qianfan")
    @ResponseBody
    public Result qianfan(String say, HttpServletRequest request) throws NoApiKeyException, ApiException, InputRequiredException {
        User user = (User) request.getAttribute("user");
        Qianfan qianfan = new Qianfan();
        try {
            // 指定模型
            ChatResponse resp = qianfan.chatCompletion()
                    .model("ERNIE-Lite-8K-0922")
                    .addMessage("user", say)
                    .execute();
            String msg = resp.getResult();
            System.out.println(msg);
            recordService.addRecord(say, msg, resp.getUsage().getTotalTokens(), user.getId());
//            return new Result(2000,"请求成功",msg);
//            String word = say+"非人类";
//            recordService.addRecord(say, word,200, user.getId());

            return new Result(2000,"请求成功",msg);
        }catch(Exception e){
            return new Result(5000,"模型调用错误："+e.getMessage(),null);
        }
    }
    // 多轮对话
    public static GenerationParam createGenerationParam(List<Message> messages) {
        return GenerationParam.builder()
                .model("qwen-turbo")
                .messages(messages)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .build();
    }

    public static GenerationResult callGenerationWithMessages(GenerationParam param) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        return gen.call(param);
    }
    public static void mutiplymessage(String[] args) {
        try {
            List<Message> messages = new ArrayList<>();

            messages.add(createMessage(Role.SYSTEM, "You are a helpful assistant."));
            for (int i = 0; i < 3;i++) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("请输入：");
                String userInput = scanner.nextLine();
                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }
                messages.add(createMessage(Role.USER, userInput));
                GenerationParam param = createGenerationParam(messages);
                GenerationResult result = callGenerationWithMessages(param);
                System.out.println("模型输出："+result.getOutput().getChoices().get(0).getMessage().getContent());
                messages.add(result.getOutput().getChoices().get(0).getMessage());
            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    private static Message createMessage(Role role, String content) {
        return Message.builder().role(role.getValue()).content(content).build();
    }
}

//    @RequestMapping("/llm/qianwen2")
//    @ResponseBody
//    public static void qianwen2() throws NoApiKeyException, ApiException, InputRequiredException {
//        Generation gen = new Generation();
//
//        List<Message> msgManager = new ArrayList<Message>();
//        Message systemMsg0 = Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
//        Message userMsg1 = Message.builder().role(Role.USER.getValue()).content("").build();
//        msgManager.add(systemMsg0);
//        msgManager.add(userMsg1);
//
//        QwenParam params = QwenParam.builder().model("qwen-turbo")
//                .messages(msgManager.get())
//                .seed(1234)
//                .topP(0.8)
//                .resultFormat("message")
//                .enableSearch(false)
//                .maxTokens(100)
//                .temperature((float)0.85)
//                .repetitionPenalty((float)1.0)
//                .build();
//        GenerationResult result = gen.call(params);
//        System.out.println(result);
//    }
//}
